<?php

namespace app\admin\controller\user;

use app\admin\library\Brand as Brandserver;
use app\common\controller\Backend;
use app\common\model\User as UserModel;
use fast\Tree;
use think\Db;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;


    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    public function imports(){
        return parent::imports();
    }
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $this->view->assign("statusList", $this->model->getStatusList());
        // 必须将结果集转换为数组
        $ruleList = collection($this->model->order('sort', 'desc')->select())->toArray();

        foreach ($ruleList as $k => &$v)
        {
            $v['name'] = __($v['username']);
        }
        unset($v);
        Tree::instance()->init($ruleList);
        $this->rulelist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
        $ruledata = [0 => __('None')];
        foreach ($this->rulelist as $k => &$v)
        {
            if (!$v['status'])
                continue;
            $ruledata[$v['id']] = $v['name'];
        }
        $this->view->assign('ruledata', $ruledata);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->field('id')
                ->where('group_id', 0)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->where('group_id', 0)
                ->limit($offset, $limit)
                ->field('id,username,mobile,money,app_key,app_secret,sort,joinip,status,pid,brand_name')
                ->select();
            foreach ($list as $k => $v) {
                $v->hidden(['password', 'salt']);
                $v['father']=Brandserver::brandFa($v['pid']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    //充值
    public function recharge($ids = ''){
        if($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if($params['money'] < 0){
                $this->error(__('参数错误'));
            }
            $user = $this->model->where(['id' => $params['id']])->find();
            $before = $user->money;
            $user->money = bcadd($user->money,$params['money']);
            $result = $user->save();
            if($result){
                Db::name('trade_log')->data([
                'user_id' => $params['id'],
                'before' => $before,
                'money' => '+'.$params['money'],
                'balance' => $user->money,
                'type' => 2,
                'add_time' =>time(),
            ])->insert();
               $this->success(); 
           }else{
             $this->error(__('充值失败'));
           }

        }
        $res = $this->model->where(array('id'=>$ids))->find();
        $this->view->assign('row', $res);
        return $this->view->fetch();
    }

    //重置密钥对
    public function reset($ids = ''){
        if($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $user = $this->model->where(['id' => $params['id']])->find();
            $user->app_key = self::getRandomString(32);
            $user->app_secret = self::getRandomString(16);
            $result = $user->save();
            if($result){
                $this->success(); 
            }else{
             $this->error(__('重置失败'));
           }

        }
        $res = $this->model->where(array('id'=>$ids))->find();
        $this->view->assign('row', $res);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $id = $params['id'];
                $params = $this->preExcludeFields($params);
               /* $arr = explode(',', $params['lonlat']);
                unset($params['lonlat']);*/
                unset($params['id']);
                /*$params['lon'] = $arr[0];
                $params['lat'] = $arr[1];*/
                $result = $this->model->where('id', $id)->update($params);
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
        }
        $row = $this->model->get($ids);
        //dump($row);exit;
        if (isset($row->lon) && isset($row->lat)) {
            $row->lonlat = $row->lon.','.$row->lat;
        }
        if (!$row)
            $this->error(__('No Results were found'));
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $this->view->assign("row", $row);
        return $this->view->fetch();
        return parent::edit($ids);
    }

    public function add($ids = NULL){

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                /*$arr = explode(',', $params['lonlat']);
                unset($params['lonlat']);
                $params['lon'] = $arr[0];
                $params['lat'] = $arr[1];*/
                $params['app_key']=self::getRandomString(32);
                $app_secret=self::getRandomString(16);
                $params['app_secret'] = $app_secret.time();
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                $password=$params['password'];
                unset($params['password']);
                $ret = $this->auth->register($params['username'], $password,$params['mobile'],$params);
                if ($ret) {
                   // $data = ['userinfo' => $this->auth->getUserinfo()];
                    $this->success(__('OK'));
                } else {
                    $this->error($this->auth->getError());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
}
